#include "cifar10dialog.h"
#include "ui_cifar10dialog.h"
#include <QFileInfo>
#include <QHBoxLayout>
#include "imagewidget.h"

#include "c_cifar10_client.h"

#include "image_data.h"

#include <QDebug>

static bool issuffixmatching(const QString &lsuffix, const QStringList &lsuffixlist)
{
    foreach (QString isuffix, lsuffixlist) {
        if(0 == isuffix.mid(2).compare(lsuffix)){
            return 1;
        }
    }
    return 0;
}

Cifar10Dialog::Cifar10Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Cifar10Dialog)
{
    ui->setupUi(this);
    ui->imgWidget->setText("ClickMe");

    connect(ui->imgWidget, &ImageWidget::imageList, this, &Cifar10Dialog::recognizeFiles);
}

Cifar10Dialog::~Cifar10Dialog()
{
    delete ui;
}

void Cifar10Dialog::recognizeFiles(const QStringList &files)
{
    QStringList suffixlist;
    suffixlist = QString("*.png;*.bmp;*.jpeg;*.jpg;*.pbm;*.pgm").split(';');

    imgFiles = files;

    for(int i = 0; i < imgFiles.size(); i++){
        QFileInfo tfileinfo(imgFiles.at(i));
        if(tfileinfo.isFile() && !issuffixmatching(tfileinfo.suffix(), suffixlist)){
            imgFiles.removeAt(i);
        }
    }

    if(imgFiles.isEmpty()){
        return;
    }

    cifar10Recognize(imgFiles);
}

void saveImageRAW(uint8_t *raw, int len)
{
    QFile image_raw("image_data.h");
    image_raw.open(QFile::ReadWrite);

    QByteArray rawHex = QByteArray::fromRawData((const char *)raw, len);

    rawHex = rawHex.toHex(' ');
    for (int i = 32; i > 0; i--) {
        rawHex.insert(i*32*9, '\n');
    }
    image_raw.write(rawHex);

    image_raw.close();
}
void Cifar10Dialog::cifar10Recognize(const QStringList &files)
{
    setCursor(Qt::WaitCursor);
    for (QString ifile : files) {
        QPixmap preview_t;
        preview_t.load(ifile);
        if (preview_t.isNull()) continue;

        ui->imgWidget->setPixmap(preview_t.scaled(256, 256));

        qDebug() << preview_t.width() << preview_t.height() << preview_t.depth() << preview_t.colorCount();
        if (preview_t.width() != 32 || preview_t.height() != 32) {
            preview_t = preview_t.scaled(32, 32);
        }

        // invoke cifar10_recgnize()
        binary_t imgDat;
        imgDat.dataLength = 32*32*3;
        imgDat.data = (uint8_t*)malloc(32*32*3);

        uint8_t *ptr = imgDat.data;
        QImage img = preview_t.toImage();
        qDebug() << img.width() << img.height() << img.depth() << img.colorCount() << img.bitPlaneCount();
        for (int i = 0; i < img.height(); i++) {
            uint8_t *line = img.scanLine(i);
            for (int j = 0; j < img.width(); j++) {
                *ptr++ = line[4*j+2];
                *ptr++ = line[4*j+1];
                *ptr++ = line[4*j];
            }
        }
//        memcpy(imgDat.data, image_data, 32*32*3);
//        saveImageRAW(imgDat.data, 32*32*3);
qDebug() << imgDat.dataLength;
//continue;
        // Call remote function
        Cifar10Result *res = cifar10_recognize(32, 32, &imgDat);

        free(imgDat.data);

        QListWidgetItem *item = new QListWidgetItem(NULL);
        item->setSizeHint(QSize(256, 40));

        QWidget *widget = new QWidget(ui->results);
        QHBoxLayout *hbox = new QHBoxLayout(widget);
        hbox->setMargin(0);
        QLabel *icon = new QLabel;
        icon->setFixedSize(32, 32);
        icon->setPixmap(preview_t);
        hbox->addWidget(icon);
        QLabel *score = new QLabel(widget);
        score->setAlignment(Qt::AlignVCenter);
        score->setText(QString("Score: %1").arg(res->score));
        hbox->addWidget(score);
        QLabel *species = new QLabel(widget);
        species->setAlignment(Qt::AlignVCenter);
        species->setText(QString("Species: %1").arg(res->label));
        hbox->addWidget(species);
        widget->setLayout(hbox);

        free(res->label);
        free(res);

        ui->results->addItem(item);
        ui->results->setItemWidget(item, widget);
    }

    setCursor(Qt::ArrowCursor);
}

void Cifar10Dialog::on_clrBtn_clicked()
{
    ui->results->clear();
    ui->imgWidget->setPixmap(QPixmap());
    ui->imgWidget->setText("ClickMe");
}

void Cifar10Dialog::on_recogBtn_clicked()
{
    on_clrBtn_clicked();

    if(imgFiles.isEmpty()){
        return;
    }

    cifar10Recognize(imgFiles);
}
